<?php 
namespace town\controller;

use town\dmod\DB;
use town\model\Post;
use town\model\Comment;
use town\base\Request;
use town\tool\Page;

/**
 * 帖子信息
 */
class PostController
{

    /**
     * 个人信息
     */
    public function show(Request $req, $id)
    {
        $args = $req->get();
        unset($args['id']);
        $query = '';
        $where = ' and 1=1 ';
        foreach ($args as $key => $value) {
            $query .= "&{$key}={$value}";
            $where .= " and `{$key}`='{$value}' ";
        }

        // 上一条
        $sql  = "select id,title from posts where id < {$id} {$where} order by id desc limit 0,1";
        $prev = DB::queryRaw($sql);
        if (empty($prev)) {
            $prev = ['link'=>'#', 'title'=>'没有啦!'];
        } else {
            $prev = ['link'=>"/post/{$prev[0]['id']}?{$query}", 'title'=>$prev[0]['title']];
        }

        // 下一条
        $sql  = "select id,title from posts where id > {$id} {$where} order by id asc limit 0,1";
        $next = DB::queryRaw($sql);
        if (empty($next)) {
            $next = ['link'=>'#', 'title'=>'没有啦!'];
        } else {
            $next = ['link'=>"/post/{$next[0]['id']}?{$query}", 'title'=>$next[0]['title']];
        }


        $info = (new Post)->postById($id);
        if (empty($info)) {
            return abort(404);
        }
        $comments = (new Comment)->commentsByPostId($id);
        $data = [
            'info'=>$info,
            'prev'=>$prev,
            'next'=>$next,
            'comments'=>$comments
        ];
        return view('home/post', $data);
    }


    /**
     * 获取博文列表
     */
    public function post_l(Request $req)
    {
        $page = $req->get('town_p', 1);
        $count= DB::table('posts')->count();
        $show = (new Page($count))->html();
        $datas= (new Post())->posts([], $page, 10);
        return view('back/post_l', ['list'=>$datas, 'pagination'=>$show]);
    }


    /**
     * 编辑博文
     */
    public function post_e(Request $req, $id = 0)
    {
        // 保存/新增
        if ($req->method() == 'POST') {

            $data = $_POST;
            $tags = $_POST['tags'];
            unset($data['tags']);
            $data['create_at'] = time();
            $data['update_at'] = time();
            $ret  = Post::save($data);

            $pid  = empty($_POST['id']) ? $ret : $_POST['id'];
            // 保存 tags TODO::移除所有tags,添加tags
            if ($pid > 0) {
                DB::table('tags_map_posts')->delete('pid', $pid);
                DB::table('tags_map_posts')->insert(['tid'=>$tags, 'pid'=>$pid]); // 暂时单标签,有时间做加载select2标签
            }

            // 保存 markdown 解析的 HTML样式
            $Parsedown = new \Parsedown();
            $html = $Parsedown->text($data['content']);
            if ($_POST['id'] < 1) {
                DB::table('posts_html')->insert(['id'=>$pid, 'html'=>$html]);
            } else {
                DB::table('posts_html')->update(['html'=>$html], 'id', $pid);
            }

            $msg  = $ret ? '成功' : '失败';
            return redirect('post_l');
        }

        // 视图
        $info = [];
        if ($id > 0) {
            $info = (new Post)->postById($id);
        }


        // TODO::获取category
        $cate = DB::table('categorys')->get();

        // TODO::获取标签
        $tags = DB::table('tags')->get();


        // 渲染视图
        return view('back/post_e', ['info'=>$info, 'cate'=>$cate, 'tags'=>$tags]);
    }


    /**
     * 博文检索
     */
    public function post_search(Request $req)
    {
        // tags
        $tags = $req->get('tags');
        if ($tags) {
            $data = (new Post)->postsByTagId($tags);
            return view('home/post_l', $data);
        }

        // cate
        $cate = $req->get('cate');
        if ($cate) {
            $data = (new Post)->postsByCateId($cate);
            return view('home/post_l', $data);
        }

        // keyword
        $keys = $req->get('keys');

        var_dump($cate, $tags, $keys);exit();



        return view('home/post_l');
    }


    /**
     * 移除博文
     */
    public function post_d($id)
    {
        $ret = (new Post)->delete($id);
        return redirect('post_l');
    }
}
